package com.zhihu.matisse.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.resultset.ResultSet;
import ohos.utils.net.Uri;

import java.util.Arrays;

/**
 * http://stackoverflow.com/a/27271131/4739220
 */

public class PathUtils {
    /**
     * Get a file path from a Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri     The Uri to query.
     * @author paulburke
     * @return path
     */

    public static String getPath(final Context context, final Uri uri) {
        // DocumentProvider
        if ("content".equalsIgnoreCase(uri.getScheme())) { // MediaStore (and general)
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) { // File
            return uri.getDecodedPath();
        }else {
            return null;
        }
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        ResultSet cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            DataAbilityPredicates dataAbilityPredicates = new DataAbilityPredicates(selection);
            dataAbilityPredicates.setWhereArgs(Arrays.asList(selectionArgs));
            cursor = DataAbilityHelper.creator(context).query(uri, projection, dataAbilityPredicates);
            if (cursor != null && cursor.goToFirstRow()) {
                final int columnIndex = cursor.getColumnIndexForName(column);
                return cursor.getString(columnIndex);
            }
        } catch (DataAbilityRemoteException e){
            L.d(e.getMessage());
        }finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
}
